package com.xzit.rental.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity responseEntity = new ResponseEntity("匿名用户无权访问！",headers,HttpStatus.UNAUTHORIZED.value());
        String result = objectMapper.writeValueAsString(responseEntity);
        response.getWriter().write(result);
    }
}